﻿// A list implements an HTML list
define([
    'Wjs/ui/widgets/foundation/ViewSingleContainer',
    'Wjs/ui/widgets/foundation/ViewMultipleContainer',
    'Wjs/ui/elements/mixins/SelectorHolder',
    'Wjs/ui/elements/mixins/MultipleContainer',
    'Wjs/ui/elements/mixins/Selectable',
    'Wjs/ui/elements/mixins/Loadable',
    'Wjs/ui/widgets/foundation/ViewSingleContainer'
],
function () {
    'use strict';

    var Loadable = Wjs.getType('Loadable');

    return Wjs.defineOnce({

        type: 'List',

        internal: {

            base: Wjs.getType('ViewMultipleContainer'),

            mixins: [
                Wjs.getType('SelectorHolder'),
                Loadable
            ],

            onBeforeTypeDefined: function () {

                // List item
                Wjs.define({

                    type: 'ListItem',

                    internal: {

                        base: Wjs.getType('ViewSingleContainer'),

                        mixins: [
                            Loadable,
                            Wjs.getType('Selectable')
                        ],

                        initialize: function () {

                            this.setTag('li');

                            this.addClass('wjs-list-item');
                        }

                    },

                    getRecord: function () {

                        return this.record;
                    }

                });
            },

            initialize: function () {

                this.setTag('ul');

                this.addClass('wjs-list');
            }
        },

        defaultItemType: 'ListItem',

        addChildItem: function (item) {

            this.addItem(

                Wjs.new(this.defaultItemType)

                    .setItem(item)
            );

            if (this.childItemAddedHandler) {

                this.childItemAddedHandler(item);
            }

            return this;
        },

        addText: function (text) {

            this.addChildItem(

                Wjs.new('Text')

                    .setText(text)
            );

            return this;
        },

        addHtml: function (html) {

            this.addChildItem(

                Wjs.new('ViewSingleContainer')

                    .setHtml(html) // Create a safe type to use the HTML
            );

            return this;
        },

        // Handles the item (not the list item) when it is added
        onChildItemAdded: function (fcn) {

            this.childItemAddedHandler = Wjs.chain(this.childItemAddedHandler, fcn);

            return this;
        }

    });

});